package com.rui.common.aspect;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制台打印请求
 *
 * @author xr
 * @email xr@qq.com
 * @date 2020-01-01 00:00:00
 */
@Slf4j
@Aspect
@Component
@Profile("dev")
public class SwaggerAspect {

    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void log() {
    }

    /**
     * 在切点之前织入
     *
     * @param joinPoint
     * @param apiOperation
     */
    @Before(value = "@annotation(apiOperation)", argNames = "joinPoint,apiOperation")
    public void doBefore(JoinPoint joinPoint, ApiOperation apiOperation) {
//        log.info("========================================== START ==========================================");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        log.info("[{}] => {}", request.getRemoteAddr(), request.getRequestURL().toString());
//        log.info("请求路径 : {}", request.getRequestURL().toString());
//        log.info("描述信息 : {}", apiOperation.value());
//        log.info("响应类型 : {}", request.getMethod());
//        log.info("执行方法 : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
//        log.info("请求地址 : {}", request.getRemoteAddr());
//        log.info("方法参数 : {}", JsonUtil.toJson(joinPoint.getArgs()));
    }

    /**
     * 在切点之后织入0
     */
    @After("log()")
    public void doAfter() {

    }

    /**
     * 环绕
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("log()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = null;
        result = proceedingJoinPoint.proceed();
        // 打印出参
//        log.info("返回数据 : {}", result == null ? null : JsonUtil.toJson(result));
        // 执行耗时
//        log.info("时间消耗 : {} ms", System.currentTimeMillis() - startTime);
//        log.info(" =========================================== END ===========================================");
        return result;
    }
}
